<template>
  <div class="modal-overlay">
    <div class="login-modal">
      <!-- 微信登录区域 -->
      <div class="wechat-section">
        <div id="wx-qrcode" ref="qrcodeContainer"></div>
      </div>

      <!-- 账号登录/注册/找回密码区域 -->
      <div class="login-section">
        <div class="close-btn" @click="handleClose">
          <i class="el-icon-close"></i>
        </div>
        <h2 class="text-2xl font-bold mb-6 text-center">欢迎来到灵次元</h2>

        <!-- 登录表单 -->
        <el-form v-if="activeTab === 'login'" :model="loginForm" class="tab-content active">
          <el-form-item class="input-group">
            <el-input
              v-model="loginForm.phone"
              placeholder="请输入手机号"
              class="input-field"
              autocomplete="off"
              @input="validateLoginForm"
            />
          </el-form-item>
          <el-form-item class="input-group">
            <el-input
              v-model="loginForm.password"
              placeholder="请输入密码"
              type="password"
              autocomplete="off"
              class="input-field"
              @input="validateLoginForm"
            />
          </el-form-item>
          <div class="wjmi">
            <a href="javascript:;" class="text-sm text-primary hover:underline" @click="switchTab('forgot')">
              忘记密码?
            </a>
          </div>
          <el-button type="primary" class="btn btn-primary" :disabled="!isLoginBtnEnabled" @click="handleLogin">
            登录
          </el-button>
          <div class="nodate">
            没有账号？
            <a href="javascript:;" class="text-primary hover:underline" @click="switchTab('register')">立即注册</a>
          </div>
        </el-form>

        <!-- 注册表单 -->
        <el-form v-if="activeTab === 'register'" :model="registerForm" class="tab-content active">
          <el-form-item class="input-group">
            <el-input v-model="registerForm.phone" placeholder="请输入手机号" class="input-field" autocomplete="off" />
          </el-form-item>
          <div class="boxbtn">
            <el-form-item class="input-group verification-code">
              <el-input v-model="registerForm.code" autocomplete="off" placeholder="请输入验证码" class="input-field" />
            </el-form-item>
            <el-button class="verification-btn" :disabled="isCodeDisabled" @click="handleGetCode('register')">
              {{ codeText }}
            </el-button>
          </div>

          <el-form-item class="input-group">
            <el-input
              v-model="registerForm.password"
              placeholder="请设置密码（6-20位字符）"
              type="password"
              class="input-field"
            />
          </el-form-item>
          <el-form-item class="input-group">
            <el-input
              v-model="registerForm.confirmPassword"
              placeholder="请确认密码"
              type="password"
              class="input-field"
            />
          </el-form-item>
          <el-form-item class="flex items-center mb-6">
            <el-checkbox v-model="registerForm.agree" class="text-gray-600" />
            <label class="text-sm">
              我已阅读并同意
              <a href="javascript:;" class="text-primary hover:underline">《用户协议》</a>
              和
              <a href="javascript:;" class="text-primary hover:underline">《隐私政策》</a>
            </label>
          </el-form-item>
          <el-button
            type="primary"
            class="btn whitespace-nowrap btn-primary"
            :disabled="!isRegisterBtnEnabled"
            @click="handleRegister"
          >
            注册
          </el-button>
          <div class="text-center confimbtn mt-4 text-sm text-gray-500">
            已有账号？
            <a href="javascript:;" class="text-primary hover:underline" @click="switchTab('login')">立即登录</a>
          </div>
        </el-form>

        <!-- 找回密码表单 -->
        <el-form v-if="activeTab === 'forgot'" :model="forgotForm" class="tab-content active">
          <el-form-item class="input-group">
            <el-input
              v-model="forgotForm.phone"
              placeholder="请输入注册手机号"
              class="input-field"
              @input="validateForgotForm"
            />
          </el-form-item>
          <div class="boxbtn">
            <el-form-item class="input-group verification-code">
              <el-input
                v-model="forgotForm.code"
                placeholder="请输入验证码"
                class="input-field"
                @input="validateForgotForm"
              />
            </el-form-item>
            <el-button class="verification-btn" :disabled="isForgotCodeDisabled" @click="handleGetCode('forgot')">
              {{ forgotCodeText }}
            </el-button>
          </div>
          <el-form-item class="input-group">
            <el-input
              v-model="forgotForm.password"
              placeholder="请设置新密码（6-20位字符）"
              type="password"
              class="input-field"
              @input="validateForgotForm"
            />
          </el-form-item>
          <el-form-item class="input-group">
            <el-input
              v-model="forgotForm.confirmPassword"
              placeholder="请确认新密码"
              type="password"
              class="input-field"
              @input="validateForgotForm"
            />
          </el-form-item>
          <el-button
            type="primary"
            class="btn btn-primary confimbtn"
            :disabled="!isForgotBtnEnabled"
            @click="handleResetPassword"
          >
            确认修改
          </el-button>
          <div class="text-center text-sm text-gray-500 contip">
            想起密码了？
            <a href="javascript:;" class="text-primary hover:underline" @click="switchTab('login')">返回登录</a>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { sendYzm, loginPhone, register, welogin, login } from '@/api/workserve'
import { resetPhone, setToken, removeToken } from '@/utils/auth'
import { Message } from 'element-ui'
import '@/assets/wxLogin.js'
import store from '@/store'

export default {
  name: 'LingCiyuanLogin',
  data() {
    return {
      // 标签页状态
      activeTab: 'login',
      // 登录表单数据
      loginForm: {
        phone: '',
        password: '',
      },
      // 注册表单数据
      registerForm: {
        phone: '',
        code: '',
        password: '',
        confirmPassword: '',
        agree: false,
      },
      // 找回密码表单数据
      forgotForm: {
        phone: '',
        code: '',
        password: '',
        confirmPassword: '',
      },
      // 验证码按钮状态
      isCodeDisabled: false,
      codeText: '获取验证码',
      isForgotCodeDisabled: false,
      forgotCodeText: '获取验证码',
      // 按钮启用状态
      isLoginBtnEnabled: false,
      // isRegisterBtnEnabled: false,
      isForgotBtnEnabled: false,
    }
  },
  computed: {
    isRegisterBtnEnabled() {
      return (
        !!this.registerForm.phone &&
        !!this.registerForm.code &&
        !!this.registerForm.password &&
        !!this.registerForm.confirmPassword &&
        this.registerForm.password === this.registerForm.confirmPassword &&
        this.registerForm.agree
      )
    },
  },
  mounted() {
    this.generateState()
  },
  methods: {
    // 切换标签页
    switchTab(tabName) {
      this.activeTab = tabName
    },
    // 关闭登录框（空实现）
    handleClose() {
      this.$emit('close')
      this.registerForm = {
        phone: '',
        code: '',
        password: '',
        confirmPassword: '',
        agree: false,
      }
      this.forgotForm = {
        phone: '',
        code: '',
        password: '',
        confirmPassword: '',
      }
      this.loginForm = {
        phone: '',
        password: '',
      }
    },
    // 登录事件（空实现）
    async handleLogin() {
      const param = {
        phone: this.loginForm.phone,
        password: this.loginForm.password,
      }
      const res = await loginPhone(param)
      setToken(res.data.token)
      this.$store.commit('SET_USER_INFO', res.data.profile)
      Message.success('登录成功')
      this.$emit('login-success')
    },
    // 注册事件（空实现）
    async handleRegister() {
      const param = {
        phone: this.registerForm.phone,
        password: this.registerForm.password,
        code: this.registerForm.code,
      }
      const res = await register(param)
      setToken(res.data.token)
      this.$store.commit('SET_USER_INFO', res.data.profile)
      Message.success('登录成功')
      this.$emit('login-success')
    },
    // 重置密码事件（空实现）
    async handleResetPassword() {
      const param = {
        phone: this.forgotForm.phone,
        new_password: this.forgotForm.confirmPassword,
        code: this.forgotForm.code,
      }
      const res = await register(param)
      setToken(res.data.token)
      this.$store.commit('SET_USER_INFO', res.data.profile)
      Message.success('登录成功')
      this.$emit('login-success')
    },
    // 获取验证码（空实现，含倒计时逻辑）
    async handleGetCode(type) {
      if (!/^[1][3-9]\d{9}$/.test(this.registerForm.phone)) {
        Message.warning('请输入正确的手机号码')
        return
      }
      const res = await sendYzm({ phone: this.registerForm.phone })
      Message.success('验证码已发送，请注意查收')
      if (type === 'register') {
        this.isCodeDisabled = true
        let countdown = 60
        const timer = setInterval(() => {
          this.codeText = `${countdown}秒后重试`
          countdown--
          if (countdown < 0) {
            clearInterval(timer)
            this.codeText = '获取验证码'
            this.isCodeDisabled = false
          }
        }, 1000)
      } else {
        this.isForgotCodeDisabled = true
        let countdown = 60
        const timer = setInterval(() => {
          this.forgotCodeText = `${countdown}秒后重试`
          countdown--
          if (countdown < 0) {
            clearInterval(timer)
            this.forgotCodeText = '获取验证码'
            this.isForgotCodeDisabled = false
          }
        }, 1000)
      }
    },
    // 登录表单验证
    validateLoginForm() {
      this.isLoginBtnEnabled = !!this.loginForm.phone && !!this.loginForm.password
    },

    // 找回密码表单验证
    validateForgotForm() {
      const { phone, code, password, confirmPassword } = this.forgotForm
      this.isForgotBtnEnabled = !!phone && !!code && !!password && !!confirmPassword && password === confirmPassword
    },
    // 生成随机状态码（防止CSRF攻击）
    generateState() {
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
      let result = ''
      for (let i = 0; i < 16; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length))
      }
      this.state = result
      this.initWechatQRCode()
    },
    async initWechatQRCode() {
      try {
        // 3. 定制二维码样式（通过CSS）
        const customStyle = `
          /* 二维码容器样式 */
          .impowerBox .qrcode {
            width: 240px;
            height: 240px;
            margin: 0 auto;
            border: 5px solid #fff;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
          }
          /* 隐藏官方标题 */
          .impowerBox .title { display: none; }
          /* 状态文字样式 */
          .impowerBox .status {
            color: #666;
            font-size: 14px;
            margin-top: 15px;
            text-align: center;
          }
          /* 底部说明文字 */
          .impowerBox .info {
            color: #999;
            font-size: 12px;
            text-align: center;
            margin-top: 8px;
          }
        `
        // 4. 将CSS转换为DataURL（用于跨域样式注入）
        const styleBlob = new Blob([customStyle], { type: 'text/css;charset=utf-8' })
        const reader = new FileReader()
        reader.onload = e => {
          // 5. 初始化微信登录组件
          // eslint-disable-next-line no-undef
          new WxLogin({
            id: 'wx-qrcode', // 容器ID
            appid: 'wx78922bad1da9bed6',
            scope: 'snsapi_login',
            redirect_uri: 'https://0dim.com/',
            state: this.state,
            self_redirect: false, // 是否在当前页面跳转
            href: e.target.result, // 自定义样式的DataURL
            width: '200', // 容器宽度
            height: '20', // 容器高度
          })

          // 6. 处理iframe权限（避免沙箱限制）
          const iframe = this.$refs.qrcodeContainer.querySelector('iframe')
          if (iframe) {
            iframe.sandbox = 'allow-forms allow-same-origin allow-scripts allow-top-navigation'
          }

          this.loading = false
        }
        reader.readAsDataURL(styleBlob)
      } catch (error) {
        this.errorMsg = `初始化失败：${error.message || '网络错误'}`
        this.loading = false
        console.error('微信二维码初始化失败：', error)
      }
    },
  },
}
</script>

<style scoped>
/* 基础样式还原 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}
.login-modal {
  width: 800px;
  background-color: white;
  border-radius: 24px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  animation: fadeIn 0.3s ease-out;
}
.wechat-section {
  width: 40%;
  background-color: #f9fafb;
  padding: 40px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-right: 1px solid #e5e7eb;
}
.login-section {
  width: 60%;
  padding: 40px;
  position: relative;
}
.tab-content {
  display: block;
}
/* 颜色变量还原 */
:root {
  --primary: #7c3aed;
  --secondary: #f59e0b;
  --gray-500: #6b7280;
  --gray-600: #4b5563;
  --gray-900: #111827;
  --border-color: #e5e7eb;
}
/* 微信登录区域样式 */
.qr-code {
  width: 180px;
  height: 180px;
  background-color: white;
  padding: 10px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid var(--border-color);
}
.qr-code img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
.text-lg {
  font-size: 18px;
}
.font-semibold {
  font-weight: 600;
}
.mb-2 {
  margin-bottom: 8px;
}
.text-sm {
  font-size: 14px;
}
.text-gray-500 {
  /* margin-top: 10px; */
  color: var(--gray-500);
}
.text-center {
  text-align: center;
}
.mb-6 {
  margin-bottom: 24px;
}
/* 登录区域标题 */
.text-2xl {
  font-size: 24px;
}
.font-bold {
  font-weight: 700;
}
/* 禁用按钮样式 */
.btn-primary[disabled] {
  opacity: 0.6;
}
/* 关闭按钮 */
.close-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f3f4f6;
  cursor: pointer;
  transition: all 0.3s;
}
.close-btn:hover {
  background-color: var(--border-color);
}
.el-icon-close {
  color: var(--gray-500);
}
/* 标签切换样式 */
.tab-switcher {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}
.el-tabs__nav {
  border-bottom: none !important;
}
.el-tab-pane {
  padding: 0 !important;
}
.el-tabs__item {
  padding: 8px 16px !important;
  margin: 0 10px !important;
  font-size: 14px !important;
  color: var(--gray-500) !important;
  position: relative;
}
.el-tabs__item.is-active {
  color: var(--primary) !important;
  font-weight: 600 !important;
}
.el-tabs__item.is-active:after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: var(--primary);
}
/* 输入框样式 */
.input-group {
  margin-bottom: 0px;
}
.nodate {
  font-size: 14px;
  margin-top: 10px;
  text-align: center;
}
.text-primary {
  color: #7c3aed;
}
.wjmi {
  width: 100%;
  text-align: right;
  padding-right: 20px;
  margin: 10px 0;
  color: #7c3aed;
  margin-bottom: 20px;
}
.input-field {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid var(--border-color);
  border-radius: 16px;
  font-size: 14px;
  transition: all 0.3s;
}
::v-deep .el-input__inner {
  border-radius: 10px !important;
  padding: 15px 15px !important;
  font-size: 14px !important;
}
::v-deep .el-input__inner:focus {
  border-color: #7c3aed;
  outline: none;
}
.boxbtn {
  display: flex;
  padding-right: 15px;

  justify-content: space-between;
}
.verification-code ::v-deep .el-input__inner {
  width: 250px;
}
.verification-btn {
  width: 100px;
  height: 36px;
  margin-top: 12.2px;
  white-space: nowrap;
  padding: 0 15px !important;
  background-color: #ede9fe !important;
  color: var(--primary) !important;
  border-radius: 8px !important;
  font-size: 14px !important;
  border: none !;
}
/* 按钮样式 */
.btn {
  width: 93%;

  padding: 12px;
  padding: 12px 0;
  /* border-radius: 16px; */
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  text-align: center;
  margin-left: 15px;
}
.btn-primary {
  background-color: #7b37e9;
  color: white !important;
  border: none !important;
  border-radius: 4px !important;
}
.btn-primary:hover {
  background-color: #6d28d9 !important;
}
.confimbtn {
  margin-top: 10px;
}
.contip {
  margin-top: 10px;
}
.items-center {
  padding-left: 17px;
}
.text-gray-600 {
  margin-right: 5px;
}
</style>
